package cn.fsd.service.impl;

import cn.fsd.domain.Suppliers;
import cn.fsd.mapper.SuppliersMapper;
import cn.fsd.query.delivery.SupplierQuery;
import cn.fsd.service.SupplierService;
import cn.fsd.util.CacheConstant;
import cn.fsd.vo.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = CacheConstant.SUPPLIER_CACHE_NAME)
public class SupplierServiceImpl implements SupplierService {

  @Autowired
  SuppliersMapper supplierMapper;

  @Cacheable(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX
      + "' + #id", unless = "#result == null")
  @Override
  public Suppliers getSupplierByID(String id) {
    return supplierMapper.selectByPrimaryKey(id);
  }

  @Cacheable(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX
      + "all'", unless = "#result == null")
  @Override
  public List<Suppliers> getAllSuppliers() {
    return supplierMapper.selectAll();
  }

  @CacheEvict(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX
      + "all'")
  @Override
  public String addNewSupplier(Suppliers supplier) {
    String id = UUID.randomUUID().toString();
    supplier.setSupplier_id(id);
    supplierMapper.insert(supplier);
    return id;
  }

  @Caching(evict = {@CacheEvict(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX + "' + #supplierId"),
      @CacheEvict(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX + "all'")})
  @Override
  public void removeSupplierById(String supplierId) {
    supplierMapper.deleteByPrimaryKey(supplierId);
  }

  @Caching(evict = {@CacheEvict(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX + "' + #supplier.supplier_id"),
      @CacheEvict(key = "'" + CacheConstant.SUPPLIER_CACHE_KEY_PREFIX + "all'")})
  @Override
  public void updateSupplier(Suppliers supplier) {
    supplierMapper.updateByPrimaryKey(supplier);
  }

  @Override
  public PageBean<Suppliers> getSuppliersByPage(SupplierQuery query) {

    PageBean<Suppliers> pageBean = new PageBean<>();

    PageHelper.startPage(query.getPageNow(), query.getPageSize());

    List<Suppliers> result = supplierMapper.getSupplierByPage(query);

    PageInfo<Suppliers> pageInfo = new PageInfo<>(result);

    pageBean.setTotalPages(pageInfo.getPages());
    pageBean.setTotalRows(pageInfo.getTotal());
    pageBean.setRowData(pageInfo.getList());

    return pageBean;
  }

  @Override
  public Suppliers getSupplierByName(String name) {
    return supplierMapper.getSupplierByName(name);
  }

  public List<Suppliers> getSuppliersByName(String name) {
    return supplierMapper.getSuppliersByName(name);
  }




}
